﻿using Materal.Utils;
using Microsoft.Extensions.Hosting;

namespace ConsoleTest.Services
{
    /// <summary>
    /// 信号量服务
    /// </summary>
    public class SemaphoreSlimService : IHostedService
    {
        private const int _maxSemaphoreCount = 2;
        private const int _maxTaskCount = 10;
        private readonly SemaphoreSlim _semaphore = new(0, _maxSemaphoreCount);
        private Task[] _tasks = [];
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Init();
            _semaphore.Release(_maxSemaphoreCount);
            await Task.CompletedTask;
        }
        public async Task StopAsync(CancellationToken cancellationToken) => await Task.CompletedTask;
        private void Init()
        {
            _tasks = new Task[_maxTaskCount];
            for (int i = 0; i < _maxTaskCount; i++)
            {
                _tasks[i] = Test(i);
            }
        }
        private async Task Test(int taskIndex)
        {
            ConsoleQueue.WriteLine($"任务{taskIndex}开始");
            await _semaphore.WaitAsync();
            try
            {
                ConsoleQueue.WriteLine($"任务{taskIndex}执行");
                Thread.Sleep(1000);
                ConsoleQueue.WriteLine($"任务{taskIndex}完成");
            }
            finally
            {
                int semaphoreCount = _semaphore.Release();
                ConsoleQueue.WriteLine($"剩余空位: {semaphoreCount}");
            }
        }
    }
}
